package net.pws.common.security.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

public class FilterNode {
    
    private Filter current;
    
    private FilterNode next;
    
    private Map<Integer, FilterNode> branches = new HashMap<Integer, FilterNode>();
    
    public FilterNode(Filter current) {
        super();
        this.current = current;
    }
    
    public Filter current() {
        return this.current;
    }
    
    public void setNext(FilterNode next) {
        this.next = next;
    }
    
    public void setNext(Filter next) {
        this.next = new FilterNode(next);
    }
    
    public void setNext(int pathEntry, FilterNode next) {
        branches.put(pathEntry, next);
    }
    
    public void setNext(int pathEntry, Filter next) {
        branches.put(pathEntry, new FilterNode(next));
    }
    
    public boolean hasNext() {
        return (next != null);
    }
    
    public FilterNode next() {
        return this.next;
    }
    
    public boolean hasNext(int pathEntry) {
        return branches.containsKey(pathEntry);
    }
    
    public FilterNode next(int pathEntry) {
        return branches.get(pathEntry);
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        current.init(filterConfig);
        next.init(filterConfig);
        for (FilterNode node : branches.values()) {
            node.init(filterConfig);
        }
    }
    
    public void destroy() {
        current.destroy();
        next.destroy();
        for (FilterNode node : branches.values()) {
            node.destroy();
        }
    }
}
